/**
 * Created by john on 2018/3/28.
 */
var express = require('express');
var router = express.Router();
const  VCODE =require("../config/code"); //错误码
const USER = require("../src/user");
const  logger = require("../cors/log").getLogger("admin");

/*pc端页面得路由*/
/* GET home page. */

router.use( function(req, res, next) {
    console.log(req.path);
    if(req.session.admin && req.session.admin.type == VCODE.type.super){
        next();
    }else if(req.headers["x-requested-with"] == "XMLHttpRequest"){
        res.send(VCODE.login)
    }else{
        res.redirect("/self/login");
    }
})


router.get('/', function(req, res, next) {
    USER.getPage({pagesize:20,currpage:0}).then(function (ret) {
        res.locals.total = ret[0] || 0;
        res.locals.list = ret[1] || [];
        res.render('index');
    }).catch(function (ret) {
        res.status(500).send('查询错误');
        next();
    })
});
router.post("/api/del",function (req,res,next) {
    if(req.body.id){
        USER.del(req.body.id).then(function (ret) {
            res.send(VCODE.success);
        }).catch(function (ret) {
            res.send(VCODE.del)
        })
    }else{
        logger.error(ret);
        res.send(VCODE.del)
    }
});

router.post("/api/getuser",function (req,res,next) {
    var currPage = +req.body.currPage || 0;
    var pageSize = +req.body.pageSize || 20;
    USER.getPage({pagesize:pageSize,currpage:currPage}).then(function (ret) {
        var data = {data:{
            total:ret[0] || 0,
            list:ret[1] || []
        }};
        data = Object.assign(data,VCODE.success);
        res.send(data);
    }).catch(function (ret) {
        logger.error(ret,currPage,pageSize);
        res.send(VCODE.db)
    })
});

router.post("/api/search",function (req,res,next) {
    var val  = req.body.val;
    USER.search(val).then(function (ret) {
        var data = {data:{
            list:ret || []
        }}
        data = Object.assign(data,VCODE.success);
        res.send(data);
    }).catch(function (ret) {
        logger.error(ret);
        res.send(VCODE.db);
    })
})

router.post("/api/update",function (req,res,next) {
    var params = req.body;
    var id = params.id || '';

    if(id && params.type != VCODE.type.super){
        delete params.id;
        var obj = {};
        for(var i in params){
            if(params[i] && i != "id" && i != '_id' && i != "name"){
                obj[i] = params[i];
            }
        }
        if(obj["password"] && obj["password"].length < 6){
            res.send(VCODE.param);
            return ;
        }
        USER.update(id,obj).then(function (ret) {
            res.send(VCODE.success);
        }).catch(function (ret) {
            logger.error(ret);
            res.send(VCODE.db);
        });
    }else{
        res.send(VCODE.param);
    }
})

module.exports = router;
